package main

import (
	"fmt"
	"os"

	"github.com/godbus/dbus/v5"
	"github.com/godbus/dbus/v5/introspect"
)

const (
	SERVICE_NAME   = "com.gitee.zinface"
	OBJECT_PATH    = "/com/gitee/zinface/PlatformIO"
	INTERFACE_NAME = "com.gitee.zinface.PlatformIO"
)

func main() {
	conn, err := dbus.ConnectSessionBus()
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	reply, err := conn.RequestName(SERVICE_NAME, dbus.NameFlagDoNotQueue)
	if err != nil {
		panic(err)
	}

	service := NewPIOBackend()
	conn.Export(service, OBJECT_PATH, INTERFACE_NAME)

	node := &introspect.Node{
		Name: SERVICE_NAME,
		Interfaces: []introspect.Interface{
			introspect.IntrospectData,
			{
				Name:    INTERFACE_NAME,
				Methods: introspect.Methods(service),
			},
		},
	}
	conn.Export(introspect.NewIntrospectable(node), OBJECT_PATH,
		"org.freedesktop.DBus.Introspectable")

	if reply != dbus.RequestNameReplyPrimaryOwner {
		fmt.Fprintln(os.Stderr, "name already taken")
		os.Exit(1)
	}

	select {}
}
